//
//  HBQTabBarView.m
//  HelloBeeQuick
//
//  Created by LiYiLin on 16/8/18.
//  Copyright © 2016年 LiYiLin. All rights reserved.
//

#import "HBQTabBarView.h"
#import "HBQTabBarButton.h"
#import <Masonry/Masonry.h>

#define KBUTTON_COUNT 4
#define KBUTTON_HEIGHT (self.bounds.size.height)

@interface HBQTabBarView()



@end

@implementation HBQTabBarView


- (instancetype)initWithFrame:(CGRect)frame {

    if (self = [super initWithFrame:frame]) {
        [self setup_UI];
    }
    return self;
}

#pragma mark - 配置界面
- (void)setup_UI {

    self.backgroundColor = KMAIN_COLOR;
    self.alpha = 0.9;
    [self setup_Button];
}


#pragma mark - 添加按钮
- (void)setup_Button {
    
    NSArray *buttonTitleArray = @[@"首页",@"闪电超市",@"购物车",@"我的"];
    NSArray *buttonNormalImageArray = @[@"v2_home",@"v2_order",@"shopCart",@"v2_my"];
    NSArray *buttonSelectedImageArray = @[@"v2_home_r", @"v2_order_r", @"shopCart_r", @"v2_my_r"];
    
    for(int i = 0; i < KBUTTON_COUNT; i++) {

        HBQTabBarButton *button = [[HBQTabBarButton alloc] initWithFrame:CGRectMake(KWIDTH / KBUTTON_COUNT * i, 0, KWIDTH / KBUTTON_COUNT, KBUTTON_HEIGHT)];
        [button setTag:i];
        [button addTarget:self action:@selector(actionButton:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:buttonTitleArray[i] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:buttonNormalImageArray[i]] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:buttonSelectedImageArray[i]]forState:UIControlStateSelected]; 
        [button setHighlighted:NO];
        
        [self addSubview:button];
        
        if (button.tag == 0) {
            button.selected = YES;
        } else {
            button.selected = NO;
        }
    }
}

- (void)actionButton:(HBQTabBarButton *)sender {

    if (sender.tag == 2) {
        [[NSNotificationCenter defaultCenter]postNotificationName:TABBAR_BUTTON_NOTIFICATION object:nil userInfo:@{@"tag":@(sender.tag)}];
        return;
    } else {
        //button上图片的动画
        CAKeyframeAnimation *btnBounceAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
        btnBounceAnimation.duration = 0.3;
        btnBounceAnimation.calculationMode = kCAAnimationCubic;
        btnBounceAnimation.values = @[@1.0,@1.2,@0.8,@1.2,@1.0];
        [sender.imageView.layer addAnimation:btnBounceAnimation forKey:@"btnBounceAnimation"];
        
        //点击当前按钮,取消其他按钮的选中状态
        [self.subviews enumerateObjectsUsingBlock:^(__kindof HBQTabBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[HBQTabBarButton class]]) {
                obj.selected = NO;
            }
        }];
        
        //当前按钮状态设置为选中状态
        sender.selected = YES;
        
    }
    
    [[NSNotificationCenter defaultCenter]postNotificationName:TABBAR_BUTTON_NOTIFICATION object:nil userInfo:@{@"tag":@(sender.tag)}];
}

@end










